import { defineStore } from "pinia";
import { ref } from "vue";
import userApi from "@/api/user";

export const useUserStore = defineStore("user", () => {
  const user = ref(null);
  const isLogin = ref(false);

  function login(token, userInfo) {
    localStorage.setItem("token", token);
    localStorage.setItem("refresh", userInfo.refresh);
    localStorage.setItem("user", JSON.stringify(userInfo));
    localStorage.setItem("expiredTime", Date.now() + 5 * 60 * 1000);
    user.value = userInfo;
    isLogin.value = true;
  }
  async function refreshtoken() {
    try {
      const response = await userApi.refreshToken({
        refresh: localStorage.getItem("refresh"),
      });
      localStorage.setItem("token", response.data.access);
      return response.data.access;
    } catch (error) {
      console.error("刷新 token 失败:", error);
      return null;
    }
  }

  function logout() {
    user.value = null;
    isLogin.value = false;
  }
  return { user, isLogin, login, logout, refreshtoken };
});
